from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from myapp.ser import *
from myapp.models import *
from django.core.paginator import Paginator
from django.contrib.auth.hashers import make_password, check_password


# Create your views here.


class TeacherAPIView(APIView):
    def get(self, request):
        page = request.GET.get('page')
        data = Teacher.objects.all()
        ser = Paginator(data, 2)
        page = ser.page(page)
        all_page = TeacherModelSerializer(page, many=True)
        return Response({
            'code': 200,
            'data': all_page.data,
            'range': [i for i in ser.page_range]
        })

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        if not username:
            return Response({'code': 10010, 'msg': '用户名不能为空'})
        if not password:
            return Response({'code': 10011, 'msg': '密码不能为空'})
        request.data['password'] = make_password(request.data.get('password'))
        ser = TeacherModelSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200, 'msg': '注册成功'})
        return Response({'code': 10012, 'msg': '注册失败'})


class Tdl(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = Teacher.objects.filter(username=username).first()
        if user:
            if check_password(password, user.password):
                return Response({"code": 200, "mes": "登录成功", "userid": user.id})
            else:
                return Response({"code": 10010, "mes": "登录失败"})
        else:
            return Response({"code": 10020, "mes": "没有该用户"})


class StudentAPIView(APIView):
    def post(self,request):
        ser = StudentModelSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 20010})